package com.sr.recitewords.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.sr.recitewords.common.enums.BizExceptionEnum;
import com.sr.recitewords.common.vo.GeneralResult;
import com.sr.recitewords.datasource.entities.SysUser;
import com.sr.recitewords.datasource.req.LoginReq;
import com.sr.recitewords.datasource.resp.LoginResp;
import com.sr.recitewords.datasource.vo.SysUserVo;
import com.sr.recitewords.exception.BizException;
import com.sr.recitewords.service.redis.RedisService;
import com.sr.recitewords.service.user.SysUserService;
import com.sr.recitewords.utils.BaseResponseInfo;
import com.sr.recitewords.utils.MD5EncryptUtils;
import com.sr.recitewords.utils.RandImageUtil;
import com.sr.recitewords.utils.ToolUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ji_sheng_hua 华夏erp
 */
@RestController
@RequestMapping(value = "/user")
@Api(tags = {"用户管理"})
public class UserController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(UserController.class);


    @Resource
    private SysUserService sysUserService;
    @Resource
    private RedisService redisService;

    private static final String BASE_CHECK_CODES = "qwertyuiplkjhgfdsazxcvbnmQWERTYUPLKJHGFDSAZXCVBNM1234567890";

    @PostMapping(value = "/login")
    @ApiOperation(value = "登录")
    public GeneralResult<LoginResp> login(@RequestBody LoginReq req) {
        LoginResp loginResp = new LoginResp();
        boolean ynStartVerificationCode = false;
        if (ObjectUtils.isEmpty(req)) {
            throw new BizException(BizExceptionEnum.LOGIN_ACCOUNT_NULL_ERROR);
        }
        if (StringUtils.isEmpty(req.getLoginAccount())) {
            throw new BizException(BizExceptionEnum.LOGIN_ACCOUNT_NULL_ERROR);
        }
        if (StringUtils.isEmpty(req.getPassword())) {
            throw new BizException(BizExceptionEnum.LOGIN_PASSWORD_NULL_ERROR);
        }
        if (ynStartVerificationCode) {
            if (StringUtils.isEmpty(req.getVerificationCode()) || StringUtils.isEmpty(req.getVerificationKey())) {
                throw new BizException(BizExceptionEnum.VERIFICATION_CODE_NULL_ERROR);
            }
            String verificationCode = redisService.getVerificationCodeByVerificationKey(req.getVerificationKey());
            if (StringUtils.isEmpty(verificationCode)) {
                throw new BizException(BizExceptionEnum.VERIFICATION_CODE_NULL_ERROR);
            }
            if (!verificationCode.equals(req.getVerificationCode())) {
                throw new BizException(BizExceptionEnum.VERIFICATION_CODE_NULL_ERROR);
            }
        }
        logger.info("============用户登录 login 方法调用开始==============");
        String loginAccount = req.getLoginAccount();
        String password = req.getPassword();
        //判断用户是否已经登录过,登录过不再处理
//        HttpServletRequest request = getRequest();
//        Object userId = redisService.getObjectFromSessionByKey(request, "userId");
        //判断登录账号是否存在
        boolean ynExistLoginAccount = sysUserService.ynExistByLoginAccount(loginAccount);
        if (ynExistLoginAccount) {
            throw new BizException(BizExceptionEnum.LOGIN_ACCOUNT_NOT_EXIST);
        }
        SysUser sysUser = sysUserService.getUserByLoginAccount(loginAccount);
        boolean ynPassWordCorrect = MD5EncryptUtils.checkEncryptHaveSalt(sysUser.getSalt() + sysUser.getPassword(), password);
        if (!ynPassWordCorrect) {
            throw new BizException(BizExceptionEnum.LOGIN_PASSWORD_ERROR);
        }
        SysUserVo sysUserVo = new SysUserVo();
        BeanUtil.copyProperties(sysUser, sysUserVo);
        //密码和盐置空
        sysUserVo.setSalt(null);
        sysUserVo.setPassword(null);
        loginResp.setSysUserVo(sysUserVo);
        String token = UUID.randomUUID().toString().replaceAll("-", "") + "";
        redisService.storageObjectBySession(token, "userId", sysUser.getUserId());
        redisService.storageObjectBySession(token, "userName", sysUser.getUserName());
        loginResp.setToken(token);
        return GeneralResult.genSuccessResult(loginResp);
    }

    @PostMapping(value = "/registerUser")
    @ApiOperation(value = "注册用户")
    public GeneralResult<LoginResp> registerUser(@RequestBody SysUserVo sysUserVo) {
        //判断信息是否都填写
        LoginResp loginResp = new LoginResp();
        String salt = UUID.randomUUID().toString().replace("-", "");
        String password = MD5EncryptUtils.encryptHaveSalt(sysUserVo.getPassword(), salt);
        //密码和盐置空
        sysUserVo.setSalt(salt);
        sysUserVo.setPassword(password);
        boolean b = sysUserService.addSysUserVo(sysUserVo);
        String token = UUID.randomUUID().toString().replaceAll("-", "") + "";
        redisService.storageObjectBySession(token, "userId", sysUserVo.getUserId());
        redisService.storageObjectBySession(token, "userName", sysUserVo.getUserName());
        loginResp.setToken(token);
        loginResp.setSysUserVo(sysUserVo);
        return GeneralResult.genSuccessResult(loginResp);
    }


    //

    @GetMapping(value = "/getSysUserVo")
    @ApiOperation(value = "获取用户信息")
    public GeneralResult<SysUserVo> getSysUserVo() {
        SysUserVo sysUserVo = sysUserService.getSysUserVoByUserId(getUserId());
        return GeneralResult.genSuccessResult(sysUserVo);
    }

    //
//    @PostMapping(value = "/getSessionUserById")
//    @ApiOperation(value = "获取用户信息")
//    public BaseResponseInfo getSessionUserById(@RequestBody BaseIdReq<String> req) throws Exception {
//        BaseResponseInfo res = new BaseResponseInfo();
//        try {
//            Map<String, Object> data = new HashMap<>();
//            SysUser sysUser = sysUserService.getUser(req.getId());
//            sysUser.setPassword(null);
//            data.put("user", sysUser);
//            res.code = 200;
//            res.data = data;
//        } catch (Exception e) {
//            e.printStackTrace();
//            res.code = 500;
//            res.data = "获取session失败";
//        }
//        return res;
//    }
//
    @GetMapping(value = "/logout")
    @ApiOperation(value = "退出")
    public GeneralResult<String> logout() {
        HttpServletRequest request = getRequest();
        redisService.deleteObjectBySession(request, "userId");
        redisService.deleteObjectBySession(request, "roleType");
        redisService.deleteObjectBySession(request, "clientIp");
        return GeneralResult.genSuccessResult("退出成功");
    }
//
//    @PostMapping(value = "/resetPwd")
//    @ApiOperation(value = "重置密码")
//    public String resetPwd(@RequestBody JSONObject jsonObject,
//                           HttpServletRequest request) throws Exception {
//        Map<String, Object> objectMap = new HashMap<>();
//        String id = jsonObject.getString("id");
//        String password = "123456";
//        String md5Pwd = Tools.md5Encryp(password);
//        int update = sysUserService.resetPwd(md5Pwd, id);
//        if (update > 0) {
//            return returnJson(objectMap, SUCCESS, ErpInfo.OK.code);
//        } else {
//            return returnJson(objectMap, ERROR, ErpInfo.ERROR.code);
//        }
//    }
//
//    @PutMapping(value = "/updatePwd")
//    @ApiOperation(value = "更新密码")
//    public String updatePwd(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
//        Integer flag = 0;
//        Map<String, Object> objectMap = new HashMap<String, Object>();
//        try {
//            String info = "";
//            String userId = jsonObject.getString("userId");
//            String oldpwd = jsonObject.getString("oldpassword");
//            String password = jsonObject.getString("password");
//            SysUser sysUser = sysUserService.getUser(userId);
//            //必须和原始密码一致才可以更新密码
//            if (oldpwd.equalsIgnoreCase(sysUser.getPassword())) {
//                sysUser.setPassword(password);
//                flag = sysUserService.updateUserByObj(sysUser); //1-成功
//                info = "修改成功";
//            } else {
//                flag = 2; //原始密码输入错误
//                info = "原始密码输入错误";
//            }
//            objectMap.put("status", flag);
//            if (flag > 0) {
//                return returnJson(objectMap, info, ErpInfo.OK.code);
//            } else {
//                return returnJson(objectMap, ERROR, ErpInfo.ERROR.code);
//            }
//        } catch (Exception e) {
//            logger.error(">>>>>>>>>>>>>修改用户ID为 ： " + jsonObject.getLong("userId") + "密码信息失败", e);
//            flag = 3;
//            objectMap.put("status", flag);
//            return returnJson(objectMap, ERROR, ErpInfo.ERROR.code);
//        }
//    }
//
//    @DeleteMapping(value = "/deleteBatch")
//    @ApiOperation(value = "批量删除通过id")
//    public String batchDeleteResource(@RequestParam("ids") String ids, HttpServletRequest request) throws Exception {
//        Map<String, Object> objectMap = new HashMap<String, Object>();
//        int delete = sysUserService.batchDeleteUser(ids, request);
//        if (delete > 0) {
//            return ResponseJsonUtil.returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
//        } else if (delete == -1) {
//            return ResponseJsonUtil.returnJson(objectMap, ErpInfo.TEST_USER.name, ErpInfo.TEST_USER.code);
//        } else {
//            return ResponseJsonUtil.returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
//        }
//    }
//
//    /**
//     * 获取全部用户数据列表
//     *
//     * @param request
//     * @return
//     */
//    @GetMapping(value = "/getAllList")
//    @ApiOperation(value = "获取全部用户数据列表")
//    public BaseResponseInfo getAllList(HttpServletRequest request) throws Exception {
//        BaseResponseInfo res = new BaseResponseInfo();
//        try {
//            Map<String, Object> data = new HashMap<String, Object>();
//            List<SysUser> dataList = sysUserService.getUser();
//            if (dataList != null) {
//                data.put("userList", dataList);
//            }
//            res.code = 200;
//            res.data = data;
//        } catch (Exception e) {
//            e.printStackTrace();
//            res.code = 500;
//            res.data = "获取失败";
//        }
//        return res;
//    }
//
//    /**
//     * 用户列表，用于用户下拉框
//     *
//     * @param request
//     * @return
//     * @throws Exception
//     */
//    @GetMapping(value = "/getUserList")
//    @ApiOperation(value = "用户列表")
//    public JSONArray getUserList(HttpServletRequest request) throws Exception {
//        JSONArray dataArray = new JSONArray();
//        try {
//            List<SysUser> dataList = sysUserService.getUser();
//            if (null != dataList) {
//                for (SysUser sysUser : dataList) {
//                    JSONObject item = new JSONObject();
//                    item.put("id", sysUser.getId());
//                    item.put("userName", sysUser.getUsername());
//                    //item.put("yAppLogin",user.getyAppLogin());
//                    dataArray.add(item);
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return dataArray;
//    }

    /**
     * 获取随机校验码
     *
     * @param response
     * @param key
     * @return
     */
    @GetMapping(value = "/randomImage/{key}")
    @ApiOperation(value = "获取随机校验码")
    public BaseResponseInfo randomImage(HttpServletResponse response, @PathVariable String key) {
        BaseResponseInfo res = new BaseResponseInfo();
        try {
            Map<String, Object> data = new HashMap<>();
            String codeNum = ToolUtils.getCharAndNum(4);
            String base64 = RandImageUtil.generate(codeNum);
            data.put("codeNum", codeNum);
            data.put("base64", base64);
            res.code = 200;
            res.data = data;
        } catch (Exception e) {
            e.printStackTrace();
            res.code = 500;
            res.data = "获取失败";
        }
        return res;
    }


}
